package com.juc.thread;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Author HK
 * @Date 2022/5/21 18:55
 * @Version 1.0
 */
public class ThreadLocalDateUtil {

    static  final  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static Date parse(String stringDate) throws ParseException {

        return sdf.parse(stringDate);
    }

    //使用threadLocal
    public static final ThreadLocal<SimpleDateFormat> sdfThread = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    public static Date parseByThreadDate(String stringDate) throws ParseException {
        return sdfThread.get().parse(stringDate);
    }


    public static void main(String[] args) {

        /**
         * 以下代码保存: Cannot format given Object as a Date
         * 原因：SimpleDateFormat是线程不安全的
         */
        for (int i = 0; i < 3; i++) {
            new Thread(() ->{
                try {
                    //System.out.println(ThreadLocalDateUtil.parse("2022-05-21 18:58:23"));
                    System.out.println(ThreadLocalDateUtil.parseByThreadDate("2022-05-21 18:58:23"));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            },String.valueOf(i)).start();
        }

    }


}
